package com.example.teachmall4.controller;

import com.example.teachmall4.entity.Users;
import com.example.teachmall4.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    // 进入登录页面
    @GetMapping("/login")
    public String login() {
        return "login";
    }

    // 登录
    @PostMapping("/login")
    public String login(@RequestParam("account") String account, @RequestParam("password") String password, HttpSession session) {
        try {
            Users loginUser = userService.login(account, password);
            if (loginUser == null) {
                return "redirect:/user/login";
            } else {
                session.setAttribute("loginUser", loginUser);
                return "redirect:/";
            }
        } catch (Exception e) {
            // 可以记录日志，这里简单处理，重定向到登录页面
            e.printStackTrace();
            return "redirect:/user/login";
        }
    }

    // 进入注册页面
    @GetMapping("/register")
    public String register() {
        return "register";
    }

    // 注册
    @PostMapping("/register")
    public String register(@RequestParam String account,
                           @RequestParam String password,
                           @RequestParam String email,
                           @RequestParam String telphone) {
        try {
            boolean re = userService.insertUser(account, password, email, telphone);
            if (re) {
                return "redirect:/user/login";
            } else {
                return "redirect:/user/register";
            }
        } catch (Exception e) {
            // 可以记录日志，这里简单处理，重定向到注册页面
            e.printStackTrace();
            return "redirect:/user/register";
        }
    }
}